#include "CSGP_EventSystem.h"

// Register listener class
void CSGP_EventSystem::RegisterClient(eventID evID, IListener* pClient)
{
	// Error checking
	if(!pClient)
		return;

	// Register database
	m_ListenerDatabase.insert(make_pair(evID, pClient));
}

// Unregister listener class
void CSGP_EventSystem::UnregisterClient(eventID evID, IListener *pClient)
{
	// Make iterator to go through clients that 
	// will receive the event
	pair<multimap<eventID, IListener*>::iterator,
		multimap<eventID, IListener*>::iterator> range;

	// Find all clients able to receive the event
	range = m_ListenerDatabase.equal_range(evID);

	// Go through the list of listeners
	for(multimap<eventID, IListener*>::iterator mmIterator = range.first;
					mmIterator != range.second; mmIterator++)
	{
		if((*mmIterator).second == pClient)
		{
			// Remove client
			mmIterator = m_ListenerDatabase.erase(mmIterator);
			break;
		}
	}
}

void CSGP_EventSystem::DispatchEvent(CEvent *pEvent)
{
	pair<multimap<eventID, IListener*>::iterator,
		multimap<eventID, IListener*>::iterator> range;

	// Find all listeners able to receive the event
	range = m_ListenerDatabase.equal_range(pEvent->GetEventID());

	for(multimap<eventID, IListener*>::iterator mmIterator = range.first;
				mmIterator != range.second; mmIterator++)
	{
		// Pass event to listener
		(*mmIterator).second->HandleEvent(pEvent);
	}
}

void CSGP_EventSystem::SendEvent(eventID evID, void* pData)
{
	// Add event to list
	CEvent newEvent(evID, pData);

	m_CurrEvents.push_back(newEvent);
}

void CSGP_EventSystem::ProcessEvents(void)
{
	// Go through list of events
	while(m_CurrEvents.size())
	{
		DispatchEvent(&m_CurrEvents.front());
		m_CurrEvents.pop_front();
	}
}

void CSGP_EventSystem::ClearEvents(void)
{
	m_CurrEvents.clear();
}

void CSGP_EventSystem::ShutdownEventSystem(void)
{
	m_ListenerDatabase.clear();
}